package site.tuluan.sp4j.module.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import site.tuluan.sp4j.common.core.component.cache.ICache;
import site.tuluan.sp4j.common.core.domain.entity.SysRoleEntity;
import site.tuluan.sp4j.common.core.service.role.IRoleService;
import site.tuluan.sp4j.module.sys.mapper.SysRoleMapper;
import site.tuluan.sp4j.module.sys.service.ISysRoleService;

import javax.annotation.Resource;
import java.util.Set;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRoleEntity> implements ISysRoleService, IRoleService {
    private static final Logger log = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    /**
     * 用户角色缓存前缀
     */
    private static final String ROLE_PREFIX = "role:";

    @Resource
    private ICache cache;

    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 获取用户所拥有的角色集
     * @param userId 用户ID
     * @return 用户所拥有的角色集
     */
    @Override
    public Set<String> getRoleByUserId(String userId) {
        // 用户的角色存储在缓存在中，如果缓存中没有的话，从数据库中取
        Set<String> roleSet = cache.getCache(ROLE_PREFIX + userId);

        if (roleSet == null || roleSet.isEmpty()) {
            roleSet = sysRoleMapper.selectRoleSetByUserId(userId);
        }
        if (!roleSet.isEmpty()) {
            cache.setCache(ROLE_PREFIX + userId, roleSet);
        }

        return roleSet;
    }
}
